//
//  NewsFatherViewController.m
//  News
//
//  Created by xalo on 16/2/29.
//  Copyright © 2016年 News. All rights reserved.
//

#import "NewsFatherViewController.h"
#import "HTTPHelper.h"
#import "ScrollPageView.h"
#import "NewsModel.h"
#import "NewsDetailViewController.h"
#import "ArticleCell.h"
#import "PictureCell.h"
#import <UIImageView+WebCache.h>
#import <Reachability.h>
#import <MJRefresh.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "FMDatabase+Database.h"
#import "PicDetialViewController.h"


@interface NewsFatherViewController ()<ScrollPageViewDelegate,Report>

@property (nonatomic,strong) NSMutableArray *newsModelArray;
@property (nonatomic,strong) NSMutableArray *scrollImageArray;
@property (nonatomic,strong) NewsModel *newsModel;  //用于给图片详情页面传值

@end

@implementation NewsFatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (self.scrollPages) {
        
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]];
        imageView.frame = CGRectMake(0, 0, width, width*0.5);
        self.tableView.tableHeaderView = imageView;
    }
    
    self.tableView.rowHeight = 127;
    
    //加载数据
    [self setData];
    
    //下拉刷新
    [self pullDownUpdate];
    //上拉加载
    [self pullUpMoreLoad];

}

#pragma mark - 视图加载
// 获取轮播图图片数组
- (NSArray *)getScrollImages {
    
    //定义数组用来存放图片
    NSMutableArray *imagesArray = [NSMutableArray array];
    
    if (self.scrollPages) {
        
        for (int i= 0; i<self.scrollPages; i++) {
            
            NewsModel *model = self.newsModelArray[i];
            
            [imagesArray addObject:model.kpic];
        }
    }
    return imagesArray;
}

- (void)setScrollPages {
    
    if (self.scrollPages) {
        
        NSArray *imagesArray = [self getScrollImages];
        
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = width * 0.5;
        ScrollPageView *scroll = [[ScrollPageView alloc] initWithFrame:CGRectMake(0, 0, width, height) images:imagesArray modelsArray:self.newsModelArray];
        scroll.delegate = self;
        self.tableView.tableHeaderView = scroll;
    }
}

// 实现轮播图页面的代理方法
- (void)pushDetailPagesWithCurrentPages:(NSInteger)currentPages {
    
    NewsModel *model = self.newsModelArray[currentPages];
    
    if ([model.category isEqualToString:@"hdpic"]) {
        
        
        PicDetialViewController *picDetailVC = [[UIStoryboard storyboardWithName:@"Picture" bundle:nil] instantiateViewControllerWithIdentifier:@"PicDetial"];
        picDetailVC.comments = model.ID;
        picDetailVC.link = model.title;
        picDetailVC.view.backgroundColor = [UIColor whiteColor];
        self.navigationController.navigationBar.translucent = NO;
        self.tabBarController.tabBar.hidden = YES;
        [self presentViewController:picDetailVC animated:YES completion:nil];
    }else{
        
        NewsDetailViewController *detailVC = [[NewsDetailViewController alloc] init];
        
        detailVC.newsModel = model;
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

#pragma mark - 加载数据
//加载数据
- (void)setData {
    
    NSArray *array = [[FMDatabase shareManager] selectNewsModelArrayWithChannel:self.channel times:0];  // 0表示加载数据库中第一条数据
    if (array == nil) {
        [self setNetworkData];
    }else{
        
        [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"http://api.sina.cn/sinago/list.json?channel=%@",self.channel] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            
            // 如果请求到新的数据,则加载新的数据
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *dict in array) {
                
                NewsModel *model = [[NewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                if (([model.category isEqualToString:@"cms"] || [model.category isEqualToString:@"hdpic"])&&(![self.newsModelArray containsObject:model])) {
                    
                    [self.newsModelArray addObject:model];
                }
            }
            
            [self setScrollPages];
            [self.tableView reloadData];
            
            [[FMDatabase shareManager] saveModel:array withChannel:self.channel];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            
            // 网络故障,加载数据库中的数据
            for (NSDictionary *dict in array) {
                
                NewsModel *model = [[NewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                if (([model.category isEqualToString:@"cms"] || [model.category isEqualToString:@"hdpic"])&&(![self.newsModelArray containsObject:model])) {
                    
                    [self.newsModelArray addObject:model];
                }
            }
            
            [self setScrollPages];
            [self.tableView reloadData];
            
//#warning 使用mubprogress提示网络不给力
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"没有网络,小编君也没有办法...";
                [hud hide:YES afterDelay:1];
            });
            
            
        }];
        
    }
}

//加载网络数据
- (void)setNetworkData {
    
    //加载网络数据
    [[HTTPHelper sharedManger] downloadNewsModelWithChannel:self.channel subCategoryArray:self.newsModelArray block:^{
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        [self setScrollPages];
        
        [self.tableView reloadData];
        
        
    } reblock:^{
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"没有网络,小编君也没有办法...";
            [hud hide:YES afterDelay:1];
        });
        
    }];
    
    
}

- (NSMutableArray *)newsModelArray {
    if (!_newsModelArray) {
        _newsModelArray = [NSMutableArray array];
    }
    return _newsModelArray;
}

- (NSMutableArray *)scrollImageArray {
    if (!_scrollImageArray) {
        _scrollImageArray = [NSMutableArray array];
    }
    return _scrollImageArray;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.newsModelArray.count - self.scrollPages;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifer1 = @"articleCell";
    UINib *articleNib = [UINib nibWithNibName:@"ArticleCell" bundle:nil];
    [tableView registerNib:articleNib forCellReuseIdentifier:identifer1];
    
    static NSString *identifer2 = @"pictureCell";
    UINib *pictureNib = [UINib nibWithNibName:@"PictureCell" bundle:nil];
    [tableView registerNib:pictureNib forCellReuseIdentifier:identifer2];
    
    NewsModel *model = self.newsModelArray[indexPath.row + self.scrollPages];
    
    if ([model.category isEqualToString:@"hdpic"] && model.picsArray.count >= 3) {
        
        PictureCell *pictureCell = [tableView dequeueReusableCellWithIdentifier:identifer2];
        pictureCell.titleLabel.text = model.title;
        pictureCell.delegate = self;
        pictureCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        extern BOOL isWiFiMode;
        Reachability *ablity = [Reachability reachabilityForInternetConnection];
        if ([ablity isReachableViaWiFi] || ([ablity isReachable] && !isWiFiMode) || ![ablity isReachable]) {
            [pictureCell.pic1 sd_setImageWithURL:[NSURL URLWithString:model.picsArray[0]] placeholderImage:[UIImage imageNamed:@"background"]];
            [pictureCell.pic2 sd_setImageWithURL:[NSURL URLWithString:model.picsArray[1]] placeholderImage:[UIImage imageNamed:@"background"]];
            [pictureCell.pic3 sd_setImageWithURL:[NSURL URLWithString:model.picsArray[2]] placeholderImage:[UIImage imageNamed:@"background"]];
        }
        
        return pictureCell;
        
    }else{
        
        ArticleCell *articleCell = [tableView dequeueReusableCellWithIdentifier:identifer1];
        articleCell.label.text = model.title;
        articleCell.detailLabel.text = model.intro;
        articleCell.delegate = self;
        articleCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        extern BOOL isWiFiMode;
        Reachability *ablity = [Reachability reachabilityForInternetConnection];
        if ([ablity isReachableViaWiFi] || ([ablity isReachable] && !isWiFiMode) || ![ablity isReachable]) {
            
            [articleCell.imageview sd_setImageWithURL:[NSURL URLWithString:model.kpic] placeholderImage:[UIImage imageNamed:@"background"]];
        }
        return articleCell;
    }

}

- (void)report {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"举报成功" preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
//    hud.labelText = @"举报成功";
//    hud.mode = MBProgressHUDModeText;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [hud hide:YES];
//    });
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsModel *model = self.newsModelArray[indexPath.row + self.scrollPages];
    
    if ([model.category isEqualToString:@"hdpic"]) {
        
        self.newsModel = model;
        
        PicDetialViewController *picDetailVC = [[UIStoryboard storyboardWithName:@"Picture" bundle:nil] instantiateViewControllerWithIdentifier:@"PicDetial"];
        
        UIBarButtonItem *collection = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:(UIBarButtonItemStylePlain) target:self action:@selector(collectionAction)];
        UIBarButtonItem *share = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:(UIBarButtonItemStylePlain) target:self action:@selector(shareAction)];
        picDetailVC.navigationItem.rightBarButtonItems = @[share,collection];
        picDetailVC.comments = model.ID;
        picDetailVC.link = model.title;
        picDetailVC.view.backgroundColor = [UIColor whiteColor];
        
        [self presentViewController:picDetailVC animated:YES completion:nil];
        
    }else{
        
        
        
        NewsDetailViewController *detailVC = [[UIStoryboard storyboardWithName:@"NewsDetailViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"detailVC"];
        
        detailVC.newsModel = model;
        
        [self presentViewController:detailVC animated:YES completion:nil];
    }
    
}

- (NewsModel *)newsModel {
    if (!_newsModel) {
        _newsModel = [[NewsModel alloc] init];
    }
    return _newsModel;
}

//收藏
- (void)collectionAction {
    
    
    [[FMDatabase shareManager] saveCollectionModel:self.newsModel withID:self.newsModel.ID];
    
}

// 分享
- (void)shareAction {
    
    NSLog(@"share");
}

#pragma mark - 下拉刷新
- (void)pullDownUpdate {
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"http://api.sina.cn/sinago/list.json?channel=%@",self.channel] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) { // 网络刷新成功
            
            [self.tableView.mj_header endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            //下拉刷新前,清空数据库中关于该子标题的数据
            [[FMDatabase shareManager] deleteNewsModelArrayByChannel:self.channel];
            // 清空内存中数据
            [self.newsModelArray removeAllObjects];
            
            NSArray *array = responseObject[@"data"][@"list"];
            
            for (NSDictionary *dict in array) {
                
                NewsModel *model = [[NewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                if (([model.category isEqualToString:@"cms"] || [model.category isEqualToString:@"hdpic"])&&(![self.newsModelArray containsObject:model])) {
                    
                    [self.newsModelArray addObject:model];
                }
                
            }
            
            [[FMDatabase shareManager] saveModel:array withChannel:self.channel];
            
            [self setScrollPages];
            [self.tableView reloadData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //网络刷新失败
            
            NSLog(@"%@",error);
            
            [self.tableView.mj_header endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }];
}

#pragma mark - 上拉加载
- (void)pullUpMoreLoad {
    
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        
        [self.tableView.mj_footer endRefreshing];
        
        NSString *pullUp = [NSString stringWithFormat:@"http://api.sina.cn/sinago/list.json?pull_times=%ld&pull_direction=up&channel=%@",self.times+=2, self.channel];
        
        [[AFHTTPSessionManager manager] GET:pullUp parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) { // 网络刷新成功
            
            NSArray *array = responseObject[@"data"][@"list"];
            
            NSMutableArray *pullUpLoadArray = [NSMutableArray array];
            for (NSDictionary *dict in array) {
                
                NewsModel *model = [[NewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                
                if ([model.category isEqualToString:@"cms"] || [model.category isEqualToString:@"hdpic"]) {
                    
                    [pullUpLoadArray addObject:model];
                }
                
            }
            
            [[FMDatabase shareManager] saveModel:array withChannel:self.channel];
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(self.newsModelArray.count , pullUpLoadArray.count)];
            
            [self.newsModelArray insertObjects:pullUpLoadArray atIndexes:indexSet];
            
            [self.tableView reloadData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //网络刷新失败
            
            NSLog(@"%@",error);
            
            NSArray *array = [[FMDatabase shareManager] selectNewsModelArrayWithChannel:self.channel times:self.times];  // 0表示加载数据库中第一条数据
            if (array != nil) {
                
                for (NSDictionary *dict in array) {
                    
                    NewsModel *model = [[NewsModel alloc] init];
                    [model setValuesForKeysWithDictionary:dict];
                    [self.newsModelArray addObject:model];
                }
            }
        }];
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = YES;
    self.tabBarController.tabBar.hidden = NO;
}



@end
